package cn.milk.servlet;

import cn.milk.dao.CategoryDAO;
import cn.milk.model.Category;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/CategoryServlet")
public class CategoryServlet extends HttpServlet {
    private CategoryDAO categoryDAO = new CategoryDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        String search = request.getParameter("search") != null ? request.getParameter("search") : "";
        int page = request.getParameter("page") != null ? Integer.parseInt(request.getParameter("page")) : 1;
        int pageSize = 3;

        try {
            if ("delete".equals(action)) {
                int id = Integer.parseInt(request.getParameter("id"));
                categoryDAO.deleteCategory(id);
                response.sendRedirect("CategoryServlet");
                return;
            }

            int totalCount = categoryDAO.getTotalCount(search);
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);
            List<Category> categories = categoryDAO.getCategories(search, page, pageSize);

            request.setAttribute("categories", categories);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("currentPage", page);
            request.getRequestDispatcher("categorymanage.jsp").forward(request, response);
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String action = request.getParameter("action");
        try {
            if ("add".equals(action)) {
                String name = request.getParameter("name");
                Category category = new Category();
                category.setName(name);
                categoryDAO.addCategory(category);
            } else if ("edit".equals(action)) {
                int id = Integer.parseInt(request.getParameter("id"));
                String name = request.getParameter("name");
                Category category = new Category();
                category.setId(id);
                category.setName(name);
                categoryDAO.updateCategory(category);
            }
            response.sendRedirect("CategoryServlet");
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }
}
